package com.weixin.paleituo.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.weixin.paleituo.R;
import com.weixin.paleituo.activity.TemplateDetailsActivity;
import com.weixin.paleituo.adapter.SharedHousePagerAdapter;
import com.weixin.paleituo.adapter.TemplateCityRecyclerAdapter;
import com.weixin.paleituo.adapter.TemplateRecyclerAdapter;
import com.weixin.paleituo.base.BaseFragment;
import com.weixin.paleituo.bean.HousesListBean;
import com.weixin.paleituo.bean.SharedHouseBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.SharedCityEvent;
import com.weixin.paleituo.eventbus.SharedTemplateClickEvent;
import com.weixin.paleituo.eventbus.SoldOutEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.HeaderAndFooterWrapper;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.RoundCircleTransform;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 共享家Fragment
 * 展示楼盘、样板间
 * 使用CoordinatorLayout布局，使界面具有灵活的滑动特性
 * 点击城市切换ViewPager整体布局，重新创建一套布局，每次点击进行整体页面创建。
 * 为了实现点击即更新ViewPager,这里具有一定的性能问题：
 * 1.取消了ViewPager的性能优化。
 * 2.每次去创建新的ViewPager所需的List<View>,不创建又可能出现OOM,虽然几率较低。
 * <p>
 * 同时 EventBus处理Adapter点击事件，切换城市，以及跳转样板间
 *
 * @author fengzhen
 * @version v1.0, 2018/4/16
 */
public class SharedHouseFragment extends BaseFragment {

    @BindView(R.id.recycler_city)
    RecyclerView mRecyclerCity;
    @BindView(R.id.viewpager_fragment_shared_house)
    ViewPager mViewpagerFragmentSharedHouse;

    private List<SharedHouseBean> mAllDataList = new ArrayList<>();
    private TemplateCityRecyclerAdapter mCityRecyclerAdapter;

    private LoadingPagerHead mLoadingPagerHead;
    private List<View> mRecyclerPageList;
    private SharedHousePagerAdapter mPagerAdapter;

    private Dialog mLoadingDialog;

    public static SharedHouseFragment newInstance() {
        Bundle args = new Bundle();
        SharedHouseFragment fragment = new SharedHouseFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View initView(Context context) {
        mLoadingPagerHead = new LoadingPagerHead(mContext) {
            @Override
            protected void close() {
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(mContext, R.layout.fragment_shared_house);
            }

            @Override
            protected void reLoading() {
                getData();
            }
        };
        return mLoadingPagerHead;
    }

    @Override
    protected void initData() {
        super.initData();

        if (!EventBus.getDefault().isRegistered(SharedHouseFragment.this)) {
            EventBus.getDefault().register(SharedHouseFragment.this);
        }

        Bundle bundle = getArguments();

        // 样板间ViewPager初始化
        mRecyclerPageList = new ArrayList<>();
        mPagerAdapter = new SharedHousePagerAdapter(mRecyclerPageList);
        mViewpagerFragmentSharedHouse.setAdapter(mPagerAdapter);
        // 城市列表初始化
        mRecyclerCity.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        mCityRecyclerAdapter = new TemplateCityRecyclerAdapter(mAllDataList);
        mRecyclerCity.setAdapter(mCityRecyclerAdapter);

        getData();
//        mTabCityFragmentSharedHouse.setupWithViewPager(mViewpagerFragmentSharedHouse);
//        // 下划线高度设为0
//        mTabCityFragmentSharedHouse.setSelectedTabIndicatorHeight(0);
    }

    @Override
    public void onDestroyView() {
        if (EventBus.getDefault().isRegistered(getContext())) {
            EventBus.getDefault().unregister(SharedHouseFragment.this);
        }
        mLoadingDialog=null;
        super.onDestroyView();
    }

    /**
     * 点击切换城市
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelectCity(SharedCityEvent cityEvent) {
        int position = cityEvent.getPosition();
        List<HousesListBean> housesList = mAllDataList.get(position).getHousesList();
//        if (housesList == null) {
            getCityHouses(position);
//        } else {
//            List<View> recyclerViews = getPageList(housesList);
//            mRecyclerPageList.clear();
//            mRecyclerPageList.addAll(recyclerViews);
//            mPagerAdapter.notifyDataSetChanged();
//        }
    }

    /**
     * 点击样板间
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onClickTemplate(SharedTemplateClickEvent templateEvent) {
        Intent intent = TemplateDetailsActivity.call2TempalteDetails(getContext(), templateEvent.getTemplateId());
        startActivity(intent);
    }

    private void getData() {
//        mLoadingPagerHead.showPagerView(Contans.STATE_LOADING);
        Observable<StatusCode<List<SharedHouseBean>>> observable = ApiUtils.getApi().getSharedHomeInfo(Contans.defaultToken);
        HttpUtil.getInstance().toSubscribe(
                observable,
                new ProgressSubscriber<List<SharedHouseBean>>(getContext()) {
                    @Override
                    protected void _onNext(StatusCode<List<SharedHouseBean>> statusCode) {
                        mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                        List<SharedHouseBean> data = statusCode.getData();
                        mAllDataList.clear();
                        mAllDataList.addAll(data);

                        // 城市选中第一个城市
                        mCityRecyclerAdapter.notifyDataSetChanged();
                        mCityRecyclerAdapter.getCityPositon(0);
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUtils.makeText(message);
                        mLoadingPagerHead.showPagerView(Contans.STATE_ERROR);
                    }
                }, "", lifecycleSubject, false, true);
    }

//    private void getCityViewPager(int position) {
//        List<HousesListBean> housesList = mAllDataList.get(position).getHousesList();
//        if (housesList == null) {
//            getCityHouses(position);
//        } else {
//            List<RecyclerView> recyclerViews = getPageList(housesList);
//            mRecyclerPageList.clear();
//            mRecyclerPageList.addAll(recyclerViews);
////            mAllDataList.get(position).setRecyclerViewList(recyclerViews)

//        }
//    }

    /**
     * 获取城市对应的楼盘数据
     */
    private void getCityHouses(final int position) {
        int id = mAllDataList.get(position).getId();

        Observable observable = ApiUtils.getApi().getCityHouses(Contans.defaultToken, id)
                .compose(RxHelper.getObservaleTransformer())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mLoadingDialog == null) {
                            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(getContext(), "");
                        }
                        mLoadingDialog.show();
                    }
                }).subscribeOn(AndroidSchedulers.mainThread());
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<HousesListBean>>(getContext()) {

            @Override
            protected void _onNext(StatusCode<List<HousesListBean>> data) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);

                List<HousesListBean> housesListBeans = data.getData();

                List<View> recyclerViews = getPageList(housesListBeans);

                mRecyclerPageList.clear();
                mRecyclerPageList.addAll(recyclerViews);
                mPagerAdapter.notifyDataSetChanged();
                mAllDataList.get(position).setHousesList(housesListBeans);

                mCityRecyclerAdapter.refreshSelectedPosition(position);
//                mAllDataList.get(position).setRecyclerViewList(recyclerViews);
            }

            @Override
            protected void _onError(String message) {
                ToastUtils.makeText(message);
                LoadingDialogUtils.closeDialog(mLoadingDialog);
            }
        }, "", lifecycleSubject, false, true);
    }

    /**
     * 使用城市的楼盘信息 创建ViewPager所需数据
     *
     * @return ViewPager数据
     */
    private List<View> getPageList(List<HousesListBean> housesList) {
        ArrayList<View> views = new ArrayList<>();
        for (int i = 0, j = housesList.size(); i < j; i++) {
            HousesListBean listBean = housesList.get(i);
//            View inflate = UIUtils.inflate(getContext(), R.layout.item_shared_recycle,
//                    mViewpagerFragmentSharedHouse, false);
//            RecyclerView view =inflate.findViewById(R.id.recycler_item_shared);
//            view.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
////            view.addItemDecoration(new GridleDecoration(getContext()));
//            TemplateRecyclerAdapter adapter = new TemplateRecyclerAdapter(listBean.getPtList(), true);
//            ImageView headerImg = (ImageView) inflate.findViewById(R.id.img_item_shared);
//            TextView tvHeader = (TextView) inflate.findViewById(R.id.tv_item_shared);
//            Glide.with(getContext())
//                    .load(listBean.getRout())
//                    .asBitmap()
//                    .error(R.mipmap.buffer)
//                    .transform(new RoundCircleTransform(getContext(), 6))
//                    .placeholder(R.mipmap.buffer)
//                    .into(headerImg);
//            tvHeader.setText(listBean.getHouses());
//            view.setAdapter(adapter);
//            views.add(inflate);

            RecyclerView view = (RecyclerView) UIUtils.inflate(getContext(), R.layout.item_shared_recycle,
                    mViewpagerFragmentSharedHouse, false);
            view.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
//            view.addItemDecoration(new SharedTemplateItemDecoration(getContext()));
            TemplateRecyclerAdapter adapter = new TemplateRecyclerAdapter(listBean.getPtList(), true);
            HeaderAndFooterWrapper<HousesListBean> wrapper = new HeaderAndFooterWrapper<>(adapter);
            View header = UIUtils.inflate(getContext(), R.layout.item_shared_header, view, false);
            ImageView headerImg = (ImageView) header.findViewById(R.id.img_item_shared_header);
            TextView tvHeader = (TextView) header.findViewById(R.id.tv_item_shared_header);
            Glide.with(getContext())
                    .load(listBean.getRout())
                    .asBitmap()
                    .error(R.mipmap.buffer)
                    .transform(new RoundCircleTransform(getContext(), 6))
                    .placeholder(R.mipmap.buffer)
                    .into(headerImg);
            tvHeader.setText(listBean.getHouses());
            wrapper.addHeaderView(header);
            view.setAdapter(wrapper);
            views.add(view);
        }
        return views;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void soldoutEvent(SoldOutEvent soldOutEvent) {
        int mtype = soldOutEvent.getMtype();
        if (mtype == Contans.SHARHOUSE_SOLDOUT_TYPE) {
            getData();
        }
    }

}
